import { Component, OnInit, ViewChild } from '@angular/core';
import { Http } from '@angular/http';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { ConfigService } from '../../../core/common/config.service';
import swal from 'sweetalert2';
import { SelectComponent } from '../../../shared/component/ng2-select/select';
import { CommonService } from '../../../core/common/common.service';
@Component({
    selector: 'app-accountmanage',
    templateUrl: './accountmanage.component.html',
    styleUrls: ['./accountmanage.component.scss']
})
export class AccountmanageComponent implements OnInit {
    @ViewChild('editAccountModal') public editAccountModal: ModalDirective;
    @ViewChild('accUserType') public accUserType: SelectComponent;
    @ViewChild('accountSubmit') public accountSubmit;
    @ViewChild('accountInput') public accountInput;
    @ViewChild('chnlLists') public chnlLists;
    @ViewChild('accEmail') public accEmail;
    // 新建和编辑界面的信息切换
    public displayMsg: any = {
        // header: '',
        // confirmBtn: ''
    };
    // 表格中展示的信息
    public tabledatas: any = {
        tableInfo: [],
        childAccountInfo: []
    };

    // 分组的参数
    public groupInfo: any = {
        // 登录账号所属的渠道信息
        custId: '',
        custName: '',
        // 当前分组参数
        editName: '',
        editId: '',
        // 弹窗（新建或者编辑）分组的条件
        newOrEdit: '',
        // 是否展开渠道分组
        isOpen: true
    };
    // 新建/编辑账号表格中的信息
    public editAccountInfo: any = {
        custName: '',
        account: '',
        userName: '',
        email: '',
        mobile: '',
        telephone: '',
        remark: '',
        userType: '',
        newOrEdit: '',
        userId: ''
    };
    // 表单验证格式错误提示
    public regularForm: any = {
        account: true,
        email: true
    };
    // 分页配置
    public config: any = {
        paging: true,
        itemsPerPage: 8,
        length: '',
        page: 1,
        maxSize: 5,
        firstText: '|<',
        previousText: '<<',
        nextText: '>>',
        lastText: '>|'
    };

    // 获取分组下的人员
    public getChnlMember() {
        // 初始化表格内容
        this.tabledatas.childAccountInfo = [];
        try {
            const chnlMember_url = this.configService.get('url') + '?service=CustUserService&method=getCustUserList';
            this.http.post(chnlMember_url, null).toPromise().then((data: any) => {
                const dataInfo = data.json();
                if (dataInfo.code === '0000') {
                    this.tabledatas.tableInfo = dataInfo.info;
                    this.config.length = this.tabledatas.tableInfo.length;
                    this.pageChanged(this.config);
                } else {
                    console.log(dataInfo.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        };
    }
    // 分页功能
    public pageChanged(event) {
        this.tabledatas.childAccountInfo = this.tabledatas.tableInfo.slice((event.page - 1) * this.config.itemsPerPage, event.page * this.config.itemsPerPage);
    }
    // 弹出新建或编辑账号窗口
    public showEditAccount(msg) {
        $.each(this.editAccountInfo, (key) => {
            this.editAccountInfo[key] = '';
        });
        this.regularForm.account = true;
        this.regularForm.email = true;
        if (msg === 'new') {
            this.editAccountInfo.newOrEdit = 'new';
            this.displayMsg = {
                header: '添加账号',
                confirmBtn: '添加'
            };
            this.editAccountInfo.custName = this.groupInfo.custName;
            this.editAccountModal.show();
        } else {
            this.editAccountInfo.newOrEdit = 'edit';
            this.displayMsg = {
                header: '编辑账号',
                confirmBtn: '修改'
            };
            const accountInfo = this.getAccountChecked();
            if (accountInfo.length === 1) {
                this.tabledatas.childAccountInfo.forEach((value) => {
                    if (value.account === accountInfo[0].account) {
                        $.each(value, (key) => {
                            this.editAccountInfo[key] = value[key];
                        });
                    }
                });
                this.editAccountInfo.custName = this.groupInfo.custName;
                this.editAccountModal.show();
            } else {
                swal('提示', '请选择其中一个账号进行编辑', 'warning').catch(swal.noop);
            }
        }
    }
    // 新建或编辑账号信息
    public editAccount(msg) {
        let editUser_url = '';
        const updataInfo: any = {
            'account': this.editAccountInfo.account,
            'name': this.editAccountInfo.userName,
            'email': this.editAccountInfo.email,
            'mobile': this.editAccountInfo.mobile,
            'telephone': this.editAccountInfo.telephone,
            'remark': this.editAccountInfo.remark,
            'userType': this.editAccountInfo.userType,
            'custId': this.groupInfo.custId
        };
        if (msg === 'new') {
            editUser_url = this.configService.get('url') + '?service=UserService&method=addUser';
        } else {
            editUser_url = this.configService.get('url') + '?service=UserService&method=updateUserInfo';
            updataInfo.userId = this.editAccountInfo.userId;
        }
        try {
            this.http.post(editUser_url, updataInfo).toPromise().then((data: any) => {
                const dataInfo = data.json();
                if (dataInfo.code === '0000') {
                    this.getChnlMember();
                    this.editAccountModal.hide();
                } else {
                    swal('失败', dataInfo.message, 'error').catch(swal.noop);
                }
            });
        } catch (e) {
            // TODO handle exception
        };
    }
    // 激活或者冻结选中的账号
    public activateAccount(msg) {
        const accountInfo = this.getAccountChecked();
        if (accountInfo.length > 0) {
            try {
                const activateAccount_url = this.configService.get('url') + '?service=UserService&method=changeUserState';
                this.http.post(activateAccount_url, { 'action': msg, 'userIds': accountInfo }).toPromise().then((data: any) => {
                    const dataInfo = data.json();
                    if (dataInfo.code === '0000') {
                        this.getChnlMember();
                    } else {
                        swal('失败', dataInfo.message, 'error').catch(swal.noop);
                    }
                });
            } catch (e) {
                // TODO handle exception
            };
        } else {
            swal('提示', '请选择至少一个账号进行操作', 'warning').catch(swal.noop);
        }
    }
    // 删除账号
    public destoryAccount() {
        const accountInfo = this.getAccountChecked();
        if (accountInfo.length === 1) {
            swal({
                title: '警告',
                text: '删除后不可恢复!',
                type: 'warning',
                showCancelButton: true,
                cancelButtonText: '取消',
                confirmButtonColor: '#4C91EA',
                confirmButtonText: '删除'
            }).then(() => {
                const destoryAccount_url = this.configService.get('url') + '?service=UserService&method=DestoryUser';
                this.http.post(destoryAccount_url, { 'userId': accountInfo[0].userId }).toPromise().then((data: any) => {
                    const dataInfo = data.json();
                    if (dataInfo.code === '0000') {
                        this.getChnlMember();
                    } else {
                        swal('失败', dataInfo.message, 'error').catch(swal.noop);
                    }
                });
            }).catch(swal.noop);
        } else {
            swal('提示', '请选择其中一个账号进行操作', 'warning').catch(swal.noop);
        }
    }
    // 重置账号密码
    public resetPwd() {
        const accountInfo = this.getAccountChecked();
        if (accountInfo.length === 1) {
            try {
                const resetPwd_url = this.configService.get('url') + '?service=UserService&method=resetUserPwd';
                this.http.post(resetPwd_url, { 'account': accountInfo[0].account }).toPromise().then((data: any) => {
                    const dataInfo = data.json();
                    if (dataInfo.code === '0000') {
                        swal('密码重置成功', '', 'success').catch(swal.noop);
                    } else {
                        swal('警告', dataInfo.message, 'warning').catch(swal.noop);
                    }
                });
            } catch (e) {
                // TODO handle exception
            };
        } else {
            swal('提示', '请选择其中一个账号进行操作', 'warning').catch(swal.noop);
        }
    }
    constructor(private http: Http, public configService: ConfigService, public commonService: CommonService) {
        // 获取成员列表
        this.getChnlMember();
        // 获取所属客户信息
        try {
            const userType_url = this.configService.get('url') + '?service=QueryInfoService&method=getCustInfoByUser';
            this.http.post(userType_url, null).toPromise().then((data: any) => {
                const dataInfo = data.json();
                if (dataInfo.code === '0000') {
                    this.groupInfo.custId = dataInfo.info.custId;
                    this.groupInfo.custName = dataInfo.info.custName;
                } else {
                    console.log(dataInfo.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        };
        // 获取权限列表
        try {
            const userType_url = this.configService.get('url') + '?service=TableDictService&method=getDictList';
            this.http.post(userType_url, { 'code': 'USER_TYPE_3' }).toPromise().then((data: any) => {
                const dataInfo = data.json();
                const selectInfo: any[] = [];
                if (dataInfo.code === '0000') {
                    dataInfo.info.forEach(value => {
                        selectInfo.push({ id: value.value, text: value.label });
                    });
                    this.accUserType.items = selectInfo;
                } else {
                    console.log(dataInfo.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        };
    }
    ngOnInit() { }
    // 获取当前表格中被选中的账号信息
    public getAccountChecked() {
        return $(this.accountInput.nativeElement).find(':checked').map(function () {
            return { account: $(this).val(), userId: $(this).attr('id') };
        }).get();
    }
    // 判断账号是否已存在
    public existAccount(msg) {
        try {
            const existAccount_url = this.configService.get('url') + '?service=UserService&method=checkUserName';
            this.http.post(existAccount_url, { 'account': msg }).toPromise().then((data: any) => {
                const dataInfo = data.json();
                if (dataInfo.code === '0000') {
                    if (dataInfo.info === true) {
                        this.regularForm.account = true;
                    } else {
                        this.regularForm.account = false;
                    }
                } else {
                    console.log(dataInfo.message);
                }
            });
        } catch (e) {
            // TODO handle exception
        };
    }
    // 对邮件的格式进行验证
    public regularInput(info) {
        if (info === 'accEmail') {
            const re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
            if (re.test(this.editAccountInfo.email)) {
                this.regularForm.email = true;
            } else {
                this.regularForm.email = false;
            }
        }
    }
    // 对输入的参数类型进行实时判断判断
    public regularType(name, value) {
        if (name === 'account') {
            return value.replace(/[^\w]/g, '')
        } else if (name === 'accMobile') {
            return value.replace(/[^\d+-]/g, '');
        }
    }
}
